package com.juzhencms.apps.busi.web;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.base.common.config.Config;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.WebUtil;

import lombok.extern.slf4j.Slf4j;


@Controller
@Slf4j
@RequestMapping("/deployNode")
public class DeployNodeController  extends BaseController{
	
	/**
	 * 获取当前用户权限范围内的节点清单(缓存管理中使用的)
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/listData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String listData(HttpServletRequest request){
		Map data=new HashMap();
		List whereParamList=new ArrayList();
		String where="where del_flag=0 and runtime=?";
		if(request.getParameter("runtime")!=null && !request.getParameter("runtime").equals("")) {
			//log.info(request.getParameter("active"));
			whereParamList.add(request.getParameter("runtime"));
		}else {
			whereParamList.add(this.getCommonService().getConfig().getValue("spring.profiles.active"));
		}
		
		//根据站点权限显示数据，管理后台和前台通用站点是都能看到的，便于清理缓存
		String siteIds="0";
		Map userMenu=this.getLoginUser().getUserMenu();
		if(userMenu!=null && userMenu.get("content")!=null) {
			Map contentMenu=(Map)userMenu.get("content");
			if(contentMenu!=null && contentMenu.get("sub")!=null) {
				List siteMenuList=(List)contentMenu.get("sub");
				if(siteMenuList!=null) {
					for(int i=0;i<siteMenuList.size();i++) {
						Map tmpSite=(Map)siteMenuList.get(i);
						siteIds+=","+tmpSite.get("id");
					}
				}
			}
		}
		where+=" and site_id in ("+siteIds+") ";
		//排序参数 
		String sortField="id";
		String sortOrder="asc";
		if(request.getParameter("sortField")!=null && !request.getParameter("sortField").equals(""))
			sortField = request.getParameter("sortField");
		if(request.getParameter("sortOrder")!=null && !request.getParameter("sortOrder").equals(""))
			sortOrder = request.getParameter("sortOrder");
		
		//查询列表数据
		//log.info("select * from "+DBTable.deployNode+" "+where+" order by "+sortField+" "+sortOrder+" limit ?,?");
		//log.info(JSON.toJSONString(whereParamList));
	
		List dataList=this.getCommonService().getJdbcDao().querySql("select id,name from "+DBTable.deployNode+" "+where+" order by "+sortField+" "+sortOrder+" limit 0,1000", whereParamList.toArray());
		
		
		//拼装返回的数据
		data.put("data", dataList.toArray());
		return WebUtil.resultString(data,request);
		
	}
	
	
	@RequestMapping(value="/gridlistData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String gridlistData(HttpServletRequest request){
		Map data=new HashMap();
		List whereParamList=new ArrayList();
		String where="where del_flag=0 and runtime=?";
		if(request.getParameter("runtime")!=null && !request.getParameter("runtime").equals("")) {
			//log.info(request.getParameter("active"));
			whereParamList.add(request.getParameter("runtime"));
		}else {
			whereParamList.add(this.getCommonService().getConfig().getValue("spring.profiles.active"));
		}
		
		//部署节点管理部分有权限的话即可显示全部数据，但编辑时的站点聚焦可能根据权限会有问题，这个模块只能分给总部角色或超级管理员
		/*//根据站点权限显示数据
		Map userPermissions=this.getLoginUser().getPermissions();
		if(userPermissions!=null && userPermissions.get("root")==null){
			String siteIds="0";
			Map userMenu=(Map)this.getLoginUser().get("userMenu");
			if(userMenu!=null && userMenu.get("content")!=null) {
				Map contentMenu=(Map)userMenu.get("content");
				if(contentMenu!=null && contentMenu.get("sub")!=null) {
					List siteMenuList=(List)contentMenu.get("sub");
					if(siteMenuList!=null) {
						for(int i=0;i<siteMenuList.size();i++) {
							Map tmpSite=(Map)siteMenuList.get(i);
							siteIds+=","+tmpSite.get("id");
						}
					}
				}
			}
			where+=" and site_id in ("+siteIds+") ";
		}*/
		
		//搜索参数
		if(request.getParameter("site_id")!=null && !request.getParameter("site_id").toString().trim().equals("")){
			where+=" and site_id = ? ";
			whereParamList.add(request.getParameter("site_id"));
		}
		
		
		if(request.getParameter("name")!=null && !request.getParameter("name").toString().trim().equals("")){
			where+=" and name like ? ";
			whereParamList.add("%"+request.getParameter("name")+"%");
		}
		
		//分页处理
		int pageIndex=1;
		if(request.getParameter("pageIndex")!=null && !request.getParameter("pageIndex").toString().trim().equals("")){
			pageIndex=new Integer(request.getParameter("pageIndex")).intValue();
		}
		int pageSize=10;
		if(request.getParameter("pageSize")!=null && !request.getParameter("pageSize").toString().trim().equals("")){
			pageSize=new Integer(request.getParameter("pageSize")).intValue();
		}
		int start=0;
		if(pageIndex>1){
			start=(pageIndex-1)*pageSize;
		}
		whereParamList.add(start);
		whereParamList.add(pageSize);
		
		//排序参数 
		String sortField="id";
		String sortOrder="asc";
		if(request.getParameter("sortField")!=null && !request.getParameter("sortField").equals(""))
			sortField = request.getParameter("sortField");
		if(request.getParameter("sortOrder")!=null && !request.getParameter("sortOrder").equals(""))
			sortOrder = request.getParameter("sortOrder");
		
		//查询列表数据
		//log.info("select * from "+DBTable.deployNode+" "+where+" order by "+sortField+" "+sortOrder+" limit ?,?");
		//log.info(JSON.toJSONString(whereParamList));
	
		List dataList=this.getCommonService().getJdbcDao().querySql("select * from "+DBTable.deployNode+" "+where+" order by "+sortField+" "+sortOrder+" limit ?,?", whereParamList.toArray());
		if(dataList!=null && dataList.size()>0){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for(int i=0;i<dataList.size();i++){
				Map row=(Map)dataList.get(i);
				Date date = (Date)row.get("update_time");
				row.put("create_time",sdf.format(date));
				
			}
		}
		
		//查询总条数
		Map countRow=this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.deployNode+" "+where, whereParamList.subList(0, whereParamList.size()-2).toArray());
		int recordsTotal=0;
		if(countRow.get("count_num")!=null){
			recordsTotal=new Integer(countRow.get("count_num").toString()).intValue();
		}
		
		//拼装返回的数据
		data.put("data", dataList.toArray());
		data.put("itemsCount", recordsTotal);
		
		
		
		return WebUtil.resultString(data,request);
	}
	
	@RequestMapping(value="/detailData/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String detailData(@PathVariable("id") String id,HttpServletRequest request){
		Map data=new HashMap();
		Map record=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.deployNode+" where id=?",new Object[]{id});	

		
		data.put("data", record);
		
		
		return WebUtil.resultString(data,request);
	}
	
	@RequestMapping(value="/save",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String save(HttpServletRequest request){
		
		
		//System.out.println(request.getParameter("data"));
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		
		data.put("update_time", new Date());
		if(data.get("runtime")==null || data.get("runtime").toString().equals("")) {
			data.put("runtime", this.getCommonService().getConfig().getValue("spring.profiles.active"));
		}
		
		if(id==null || id.equals("")){
			this.getCommonService().getJdbcDao().addObj(DBTable.deployNode, data);
		}else{
			this.getCommonService().getJdbcDao().updateObj(DBTable.deployNode, data, "id");
		}
		
		Map result=new HashMap();
		result.put("result", 1);
		result.put("msg", "保存成功");
		
		
		return WebUtil.resultString(result,request);
		
	}
	
	@RequestMapping(value="/delete",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String delete(HttpServletRequest request){

		
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		
		
		if(id==null || id.equals("")){
		}else{	
	        String[] idArray = id.split(",");
	        String tmpVar="?";
	        if(idArray!=null && idArray.length>0){
	        	Matcher matcher = Pattern.compile("\\d+").matcher(id);
	        	tmpVar=matcher.replaceAll("?");
	        }
	        
	        
	        
			this.getCommonService().getJdbcDao().updateSql("update "+DBTable.deployNode+" set del_flag=1 where id in ("+tmpVar+")",idArray);
		}
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
	@RequestMapping(value="/updatePosition",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String updatePosition(HttpServletRequest request){
		
		if(request.getParameter("position")==null || request.getParameter("id")=="")
			return "";
		
		this.getCommonService().getJdbcDao().updateSql("update "+DBTable.deployNode+" set position=? where id=?",new Object[]{request.getParameter("position"),request.getParameter("id")});
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
	
	
	
}
